package com.jingan.nursinghome.regulatory.dialog;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jingan.nursinghome.regulatory.MainActivity;
import com.jingan.nursinghome.regulatory.R;
import com.jingan.nursinghome.regulatory.data.MicrometerTable;
import com.jingan.nursinghome.regulatory.dialog3.CreateMicrometerTableDailog3;
import com.jingan.nursinghome.regulatory.http.Http;
import com.jingan.nursinghome.regulatory.model.Topic;
import com.jingan.nursinghome.regulatory.view.BitmapsView;
import com.jingan.nursinghome.regulatory.view.MyActionBar;
import com.jingan.nursinghome.regulatory.view.PageView;
import com.jingan.nursinghome.regulatory.view.QianmiView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.android.support.v7.lib.sin.crown.base.BaseActivity;
import cn.android.support.v7.lib.sin.crown.base.BaseApplication;
import cn.android.support.v7.lib.sin.crown.base.BaseDialog;
import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.base.BasePhotoActivity;
import cn.android.support.v7.lib.sin.crown.base.BasePhotoListenner;
import cn.android.support.v7.lib.sin.crown.dialog.AlertDialog;
import cn.android.support.v7.lib.sin.crown.dialog.PhotoDialog;
import cn.android.support.v7.lib.sin.crown.dialog.ProgressDailog;
import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils;
import cn.android.support.v7.lib.sin.crown.utils.CacheUtils;
import cn.android.support.v7.lib.sin.crown.utils.UtilAssets;
import cn.android.support.v7.lib.sin.crown.utils.UtilCache;
import cn.android.support.v7.lib.sin.crown.utils.UtilNumber;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.UtilTime;
import cn.android.support.v7.lib.sin.crown.utils.UtilToast;

/**
 * 千分表提交界面
 * Created by 彭治铭 on 2017/10/19.
 */

public class CommitDailog extends BaseDialog {

    MicrometerTableOSDialog micrometerTableOSDialog;

    public CommitDailog(BaseActivity baseActivity, MicrometerTableOSDialog micrometerTableOSDialog) {
        init(baseActivity, R.layout.dialog_micrometertablleos_commit, false, false);
        window.setWindowAnimations(cn.android.support.v7.lib.sin.crown.R.style.Crown_Window_right);
        this.micrometerTableOSDialog = micrometerTableOSDialog;
        initUI();
        adapterUI();
        initZ();
    }

    private void initZ() {
        TextView txt_zhengai = (TextView) findViewById(R.id.txt_zhengai);
        ProportionUtils.getInstance().adapterTextView(txt_zhengai);
        txt_zhengai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Topic> mTopics = new ArrayList<Topic>();
                for (int i = 0; i < MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).size(); i++) {
                    String zhengai = MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getZhengai().trim();
                    if (!zhengai.equals("0")) {
                        mTopics.add(MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i));
                    }
                }
                for (int i = 0; i < MicrometerTable.getInstance().getHostoryQFTopics().size(); i++) {
                    String zhengai = MicrometerTable.getInstance().getHostoryQFTopics().get(i).getZhengai().trim();
                    if (!zhengai.equals("0")) {
                        mTopics.add(MicrometerTable.getInstance().getHostoryQFTopics().get(i));
                    }
                }
                if (mTopics.size() > 0) {
                    ZhangaiXiangDialog.getInstance(baseActivity, mTopics, 0, new BaseListenner() {
                        @Override
                        public void onResult(Object result) {
                            MicrometerTableOSDialog.micrometerTableOSDialog.updateAdapter();

                            int score = 0;//得分。
                            int maxScore = 0;//总分
                            //当前题目的得分和总分
                            for (int i = 0; i < MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog
                                    .jlyName).size(); i++) {
                                maxScore = maxScore + Integer.valueOf(MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog
                                        .jlyName).get(i).getMaxScore());
                                String c = MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog
                                        .jlyName).get(i).getCscore();
                                if (c != null && !c.trim().equals("")) {
                                    score = score + Integer.valueOf(c);
                                }
                            }
                            //历史整改的得分和总分
                            if (MicrometerTable.getInstance().getHostoryQFTopics().size() > 0) {
                                for (int i = 0; i < MicrometerTable.getInstance().getHostoryQFTopics().size(); i++) {
                                    maxScore = maxScore + Integer.valueOf(MicrometerTable.getInstance().getHostoryQFTopics().get(i).getMaxScore());
                                    String c = MicrometerTable.getInstance().getHostoryQFTopics().get(i).getCscore();
                                    if (c != null && !c.trim().equals("")) {
                                        score = score + Integer.valueOf(c);
                                    }
                                }
                            }
                            mScore = score + "";
                            mMaxScore = maxScore + "";
                            txt_hdfs2.setText(mScore + "分/" + mMaxScore + "分");//得分
                            rate = UtilNumber.getInstance().getPercent(Integer.valueOf(mScore), Integer.valueOf(mMaxScore), 2);
                            txt_hdfs4.setText(rate);//得分率
                        }
                    });
                } else {
                    UtilToast.showToastView("暂无整改项");
                }
            }
        });
    }

    private static CommitDailog commitDailog;

    static String mScore;//得分。
    static String mMaxScore;//总分

    public static CommitDailog getInstance(BaseActivity baseActivity, MicrometerTableOSDialog micrometerTableOSDialog, String maxScore, String score) {
        mScore = score;
        mMaxScore = maxScore;
        if (isFinishing(commitDailog)) {
            commitDailog = new CommitDailog(baseActivity, micrometerTableOSDialog);
        }
        return commitDailog;
    }

    MyActionBar myActionBar;
    TextView txt_hostory, txt_select, txt_next;

    TextView txt_hdfs2;//得分
    TextView txt_hdfs4;//得分率
    TextView txt_xunjian;//巡检表类型
    TextView txt_jigou;//巡检机构
    TextView txt_time;//巡检时间
    TextView txt_goutou;//主要沟通人员
    EditText txt_beizhu2;//备注

    Button btn_img;//上传照片
    Button btn_qianmi;//签名

    BitmapsView bitmapsView;//位图显示

    private void initUI() {
        myActionBar = (MyActionBar) findViewById(R.id.MyActionBar);
        myActionBar.setLeftBimapAndTitle(null, "评分结果");
        myActionBar.setBaseListennerLeft(new BaseListenner() {
            @Override
            public void onResult(Object result) {
                onBack();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onBack();
                    return true;//记得返回true。表示已经处理。
                }
                return false;//返回键以外交给系统自行处理。不可以屏蔽，不然输入法键盘的按键可能无效。如删除键
            }
        });

        txt_hostory = (TextView) findViewById(R.id.txt_hostory);
        txt_select = (TextView) findViewById(R.id.txt_select);
        txt_next = (TextView) findViewById(R.id.txt_next);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.txt_hostory://上一项
                        dismiss();
                        break;
                    case R.id.txt_select://选题
                        XuantiDialog.getInstance(baseActivity, new BaseListenner<Integer>() {
                            @Override
                            public void onResult(Integer result) {
                                //返回当前页面
                                micrometerTableOSDialog.pageIndex = result;
                                //recyclerView.smoothScrollToPosition(pageIndex);
                                //linearLayoutManager.scrollToPosition(pageIndex);
                                micrometerTableOSDialog.linearLayoutManager.scrollToPositionWithOffset(micrometerTableOSDialog.pageIndex - 1, 0);
                                dismiss();
                            }
                        });
                        break;
                    case R.id.txt_next://提交
                        //虚假打分，模拟提交。
//                        for (int i = 0; i < MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).size(); i++) {
//                            MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).setCscore("4");
//                            Log.e("test", "分数:\t" + MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getCscore());
//                        }
//                        if (MicrometerTableOSDialog.micrometerTableOSDialog.tihao.equals("") || true) {//true测试提交
                        if (MicrometerTableOSDialog.micrometerTableOSDialog.tihao.equals("")) {
                            if (QMbitmap == null || QMbitmap.isRecycled()) {
                                baseActivity.SnackbarMake("签名不能为空!", true, findViewById(R.id.dialog_micrometertableos_constraintLayout));
                                break;
                            }
                            //提交
                            Map<String, String> map = new HashMap<>();
                            Map<String, File> fileMap = new HashMap<>();
                            map.put("oid", MicrometerTable.getInstance().getJlyID(CreateMicrometerTableDailog.jlyName));//敬老院机构ID
                            map.put("nameid", MicrometerTable.getInstance().getUser().getId());//巡检人ID
                            //Log.e("test", "巡检人ID:\t" + MicrometerTable.getInstance().getUser().getId());
                            String t = UtilTime.getInstance().getAbsoluteTime(" HH:mm:ss");
                            map.put("routing_inspection_time", CreateMicrometerTableDailog.time + t);//巡检时间
                            //主要沟通人员ID
                            String[] lids = CreateMicrometerTableDailog.names.split("、");
                            String lids2 = "";
                            for (int i = 0; i < lids.length; i++) {
                                String id = MicrometerTable.getInstance().getLinkupID(lids[i]);
                                if (i == 0) {
                                    lids2 = id;
                                } else {
                                    lids2 = lids2 + "," + id;
                                }
                            }
                            map.put("lid", lids2);//主要沟通人员id
                            map.put("remark", txt_beizhu2.getText().toString());//备注
                            File file = UtilAssets.getInstance(baseActivity).saveBitmap(QMbitmap, baseActivity.getApplicationContext().getFilesDir().getAbsolutePath(), MicrometerTable.getInstance().getUser().getId() + CreateMicrometerTableDailog.time + ".png");
                            //Log.e("test", "文件:\t" + file.getName() + "\t大小:\t" + file.length());
                            fileMap.put("signature", file);//签名
                            map.put("otherpeople", CreateMicrometerTableDailog.other);//其他
                            //多图片资源
                            for (int i = 0; i < files.size(); i++) {
                                if (i == 0) {
                                    fileMap.put("polling_img_yi", files.get(i));
                                }
                                if (i == 1) {
                                    fileMap.put("polling_img_er", files.get(i));
                                }
                                if (i == 2) {
                                    fileMap.put("polling_img_san", files.get(i));
                                }
                                if (i == 3) {
                                    fileMap.put("polling_img_si", files.get(i));
                                }
                                if (i == 4) {
                                    fileMap.put("polling_img_wu", files.get(i));
                                }
                            }
                            JSONArray jsonArray2 = new JSONArray();
                            JSONObject jsonObject2 = new JSONObject();
                            try {
                                int index = 0;
                                //当前题目集合
                                for (int i = 0; i < MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).size(); i++) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("sid", MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getId());//题目ID
                                    //0无整改，1现场整改，2计划整改。
                                    jsonObject1.put("sp_type", MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getZhengai().trim());
                                    jsonObject1.put("remark", MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getRemark());
                                    jsonObject1.put("pscore", MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getCscore());
                                    jsonArray2.put(i, jsonObject1);
                                    index = i;

                                    //Log.e("test","题目ID:\t"+MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getId()+"\t整改:\t"+MicrometerTable.getInstance().getTopics(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName).get(i).getZhengai().trim());
                                }
                                //历史整改题目集合
                                if (MicrometerTable.getInstance().getHostoryQFTopics().size() > 0) {
                                    for (int i = 0; i < MicrometerTable.getInstance().getHostoryQFTopics().size(); i++) {
                                        JSONObject jsonObject1 = new JSONObject();
                                        jsonObject1.put("sid", MicrometerTable.getInstance().getHostoryQFTopics().get(i).getId());//题目ID
                                        //0无整改，1现场整改，2计划整改。
                                        jsonObject1.put("sp_type", MicrometerTable.getInstance().getHostoryQFTopics().get(i).getZhengai().trim());
                                        jsonObject1.put("remark", MicrometerTable.getInstance().getHostoryQFTopics().get(i).getRemark());
                                        jsonObject1.put("pscore", MicrometerTable.getInstance().getHostoryQFTopics().get(i).getCscore());
                                        index++;
                                        jsonArray2.put(index, jsonObject1);

                                        //Log.e("test","题目ID2:\t"+ MicrometerTable.getInstance().getHostoryQFTopics().get(i).getId()+"\t整改:\t"+ MicrometerTable.getInstance().getHostoryQFTopics().get(i).getZhengai().trim());

                                    }
                                }

                                jsonObject2.put("subject_list", jsonArray2);
                            } catch (JSONException e) {
                                Log.e("test", "题目集合json异常:\t" + e.getMessage());
                            }
                            //Log.e("test", "题目集合:\t\n" + jsonObject2.toString());
                            map.put("subject_list", jsonObject2.toString());//巡检题目集合(参数为下面两个sid,sp_type请求参数)示例:如下
                            map.put("rid", CreateMicrometerTableDailog.rid);//题目类型
                            map.put("total", mMaxScore);//总分
                            map.put("scoring_rate", rate);//得分率
                            ProgressDailog.getInstance(baseActivity);
                            Http.getInstance().CommitQF(map, fileMap, new BaseListenner<String>() {
                                @Override
                                public void onResult(final String result) {
                                    if (micrometerTableOSDialog != null) {
                                        micrometerTableOSDialog.dismiss();
                                    }
                                    dismiss();
                                    ProgressDailog.getInstance(baseActivity).dismiss();
//                                    if(MicrometerTable.getInstance().topicsHostoryQF!=null&&MicrometerTable.getInstance().topicsHostoryQF.size()>0){
//                                        MicrometerTable.getInstance().topicsHostoryQF.clear();//清空千分表历史整改记录。
//                                    }
                                    MicrometerTable.getInstance().saveHostoryQFTopics();//缓存历史整改记录。

                                    //提交之后，清除题目状态。
                                    MicrometerTable.getInstance().topics.clear();
                                    CacheUtils.getInstance().remove(MicrometerTable.getInstance().getTopicsMark(CreateMicrometerTableDailog.rid, CreateMicrometerTableDailog.jlyName));

                                    //清除画板
                                    QianmiDialog.clear();
                                    if(QMbitmap!=null&&!QMbitmap.isRecycled()){
                                        QMbitmap.recycle();
                                    }
                                    QMbitmap = null;

                                    if(files!=null&&files.size()>0){
                                        files.clear();
                                    }

                                    //位图内存释放
                                    if (bitmaps != null) {
                                        for (int i = 0; i < bitmaps.size(); i++) {
                                            if (bitmaps.get(i) != null && !bitmaps.get(i).isRecycled()) {
                                                bitmaps.get(i).recycle();
                                            }
                                        }
                                        bitmaps.clear();
                                        baseActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                bitmapsView.setBitmaps(bitmaps);
                                            }
                                        });
                                    }

                                    baseActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            UtilToast.showToastView(result);
                                        }
                                    });
                                }
                            });

                        } else {
                            //还有题目没做完
                            baseActivity.SnackbarMake("未评分的题号如下:" + MicrometerTableOSDialog.micrometerTableOSDialog.tihao, true, findViewById(R.id.dialog_micrometertableos_constraintLayout), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    XuantiDialog.getInstance(baseActivity, new BaseListenner<Integer>() {
                                        @Override
                                        public void onResult(Integer result) {
                                            //返回当前页面
                                            micrometerTableOSDialog.pageIndex = result;
                                            //recyclerView.smoothScrollToPosition(pageIndex);
                                            //linearLayoutManager.scrollToPosition(pageIndex);
                                            micrometerTableOSDialog.linearLayoutManager.scrollToPositionWithOffset(micrometerTableOSDialog.pageIndex - 1, 0);
                                            dismiss();
                                        }
                                    });
                                }
                            });
                        }
                        break;
                }
            }
        };
        txt_hostory.setOnClickListener(onClickListener);
        txt_select.setOnClickListener(onClickListener);
        txt_next.setOnClickListener(onClickListener);

        txt_hdfs2 = (TextView) findViewById(R.id.txt_hdfs2);
        txt_hdfs4 = (TextView) findViewById(R.id.txt_hdfs4);
        txt_xunjian = (TextView) findViewById(R.id.txt_xunjian);
        txt_jigou = (TextView) findViewById(R.id.txt_jigou);
        txt_time = (TextView) findViewById(R.id.txt_time);
        txt_goutou = (TextView) findViewById(R.id.txt_goutou);
        txt_beizhu2 = (EditText) findViewById(R.id.txt_beizhu2);

        bitmapsView = (BitmapsView) findViewById(R.id.bitmaps);

        btn_img = (Button) findViewById(R.id.btn_img);
        btn_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上传照片
                if (BasePhotoActivity.SnakbarView == null) {
                    BasePhotoActivity.SnakbarView = btn_img;
                }
                PhotoDialog.getInstance(MainActivity.mainActivity, true, new BasePhotoListenner() {
                    @Override
                    public void onSuccess(File file, Bitmap bitmap) {
                        if (bitmaps.size() < 5) {
                            bitmaps.add(bitmap);
                            files.add(file);
                        } else {
                            bitmaps.remove(4);
                            bitmaps.add(4, bitmap);
                            files.add(4, file);
                        }
                        bitmapsView.setBitmaps(bitmaps);
                    }
                });
            }
        });

        btn_qianmi = (Button) findViewById(R.id.btn_qianmi);
        btn_qianmi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //签名
                QianmiDialog.getInstance(baseActivity, new BaseListenner<Bitmap>() {
                    @Override
                    public void onResult(Bitmap result) {
                        QMbitmap = result;
                    }
                });
            }
        });

    }

    Bitmap QMbitmap;

    public List<Bitmap> bitmaps = new ArrayList<>();//位图数组
    public List<File> files = new ArrayList<>();//位图文件数组

    private void adapterUI() {
        ProportionUtils.getInstance().adapterScreen(baseActivity, findViewById(R.id.dialog_micrometertableos_constraintLayout));
        ProportionUtils.getInstance().adapterTextView(txt_hostory);
        ProportionUtils.getInstance().adapterTextView(txt_select);
        ProportionUtils.getInstance().adapterTextView(txt_next);
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_hdfs));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_beizhu));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_btn_img));
        ProportionUtils.getInstance().adapterTextView(txt_hdfs2);
        ProportionUtils.getInstance().adapterTextView(txt_xunjian);
        ProportionUtils.getInstance().adapterTextView(txt_jigou);
        ProportionUtils.getInstance().adapterTextView(txt_time);
        ProportionUtils.getInstance().adapterTextView(txt_goutou);
        ProportionUtils.getInstance().adapterTextView(txt_beizhu2);

        ProportionUtils.getInstance().adapterButton(btn_img);
        ProportionUtils.getInstance().adapterButton(btn_qianmi);

        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_hdfs3));
        ProportionUtils.getInstance().adapterTextView(txt_hdfs4);
    }

    String rate = "";//得分率

    @Override
    protected void listener() {
        txt_hdfs2.setText(mScore + "分/" + mMaxScore + "分");
        rate = UtilNumber.getInstance().getPercent(Integer.valueOf(mScore), Integer.valueOf(mMaxScore), 2);
        txt_hdfs4.setText(rate);
        txt_xunjian.setText("巡检表类型：千分表");
        txt_jigou.setText("巡检机构：" + CreateMicrometerTableDailog.jlyName);
        txt_time.setText("巡检时间：" + CreateMicrometerTableDailog.time);
        txt_goutou.setText("主要沟通人员:\t" + CreateMicrometerTableDailog.names);

        bitmapsView.setBaseListener(new BaseListenner<Integer>() {
            @Override
            public void onResult(Integer result) {
                bitmaps.remove((int) result);
                files.remove((int) result);
                bitmapsView.setBitmaps(bitmaps);
            }
        });
    }

    AlertDialog alertDialog;

    void onBack() {
        alertDialog = AlertDialog.getInstance(baseActivity, false, false).setTitle("提示").setMession("是否退出本次评分?\n(我们将自动保存评分记录)");
        alertDialog.setPositive("是", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                micrometerTableOSDialog.dismiss();
                alertDialog.dismiss();
            }
        });
    }

    @Override
    protected void recycleView() {

    }
}
